import React, {
  useEffect,
  useImperativeHandle,
  useState,
} from 'react';
import {View, Dimensions, StyleSheet} from 'react-native';
import {Canvas, Rect, LinearGradient, vec} from '@shopify/react-native-skia';
import {
  useSharedValue,
  useDerivedValue,
  withRepeat,
  withTiming,
  interpolate,
} from 'react-native-reanimated';
import {
  Camera,
  useCameraDevice,
  useCodeScanner,
} from 'react-native-vision-camera';
import {
  RouteProp,
  useIsFocused,
  useNavigation,
  useRoute,
} from '@react-navigation/native';
import NativeRinging from '~/specs/NativeRinging';
import {t} from 'i18next';
import {useAppTheme, Text} from 'tsun-smart-ui';
import {SkiaMask} from './Mask';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import { hexWithOpacity } from '@/utils';
const {width: SCREEN_WIDTH, height: SCREEN_HEIGHT} = Dimensions.get('window');
const scanBoxSize = Dimensions.get('window').width - 135; // 扫描框的大小
const CORNER_RADIUS = 12; // 扫描框的圆角大小

export default ({
  ref,
}: {
  ref: React.RefObject<{
    setOpen: (open: 'off' | 'on') => void;
  } | null>;
}) => {
  const route = useRoute<RouteProp<any>>();
  const setupNetworkOnly = route.params?.setupNetworkOnly ?? false;
  const isFocused = useIsFocused();
  const device = useCameraDevice('back');
  const isActive = isFocused;
  const theme = useAppTheme();
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const [open, setOpen] = useState<'off' | 'on'>('off');
  const onCodeScanned = (codes: any[]) => {
    if (codes.length > 0) {
      NativeRinging.ringing(1057);
      const code = codes[0].value;
      navigation.navigate('SNCode', {
        code,
        category: route.params?.category,
        station: route.params?.station,
        setupNetworkOnly,
      });
    }
  };
  useImperativeHandle(
    ref,
    () => ({
      setOpen: (value: 'off' | 'on') => {
        setOpen(value);
      },
    }),
    [],
  );
  const codeScanner = useCodeScanner({
    codeTypes: [
      'ean-13',
      'code-128',
      'qr',
      'aztec',
      'codabar',
      'code-39',
      'code-93',
      'data-matrix',
      'ean-8',
      'itf',
      'pdf-417',
      'upc-a',
      'upc-e',
    ],
    onCodeScanned,
  });

  const yOffset = useSharedValue(0); // 扫描光条的 Y 轴偏移量
  // 扫描光条动画
  useEffect(() => {
    yOffset.value = withRepeat(
      withTiming(scanBoxSize, {duration: 2000}), // 2s 从上到下
      -1, // 无限循环
      false, // 不反向
    );
  }, [yOffset]);

  // 动态计算光条的 Y 位置
  const animatedYOffset = useDerivedValue(() => yOffset.value);

  // 动态计算光条的透明度
  const opacity = useDerivedValue(() =>
    interpolate(
      yOffset.value,
      [0, scanBoxSize / 2, scanBoxSize],
      [0.2, 1, 0.2],
    ),
  );

  // 确定扫描光条的颜色
  const scanLineColor = theme.colors?.brand?.primary!;

  // 计算扫描框的位置
  const scanBoxLeft = (SCREEN_WIDTH - scanBoxSize) / 2;
  const scanBoxTop = (SCREEN_HEIGHT - scanBoxSize) / 2 - 30; // 稍微向上偏移
  return (
    <>
      <View style={[styles.container]}>
        {/* 相机预览 */}
        {device && (
          <Camera
            device={device}
            preview={true}
            key={isActive + ''}
            style={[StyleSheet.absoluteFill]}
            codeScanner={codeScanner}
            isActive={isActive}
            torch={open}
          />
        )}
        {/* 半透明遮罩层 - 覆盖整个屏幕，但在扫描框区域有一个透明的"洞" */}
        {/* 扫描框 - 只有边框 */}
        <View
          style={[
            styles.scanBox,
            {
              borderColor: theme.colors?.border?.primary,
              position: 'absolute',
              top: scanBoxTop,
              left: scanBoxLeft,
              backgroundColor: 'transparent', // 透明背景
            },
          ]}>
          {/* 扫描光条 */}
          <Canvas style={StyleSheet.absoluteFill}>
            <Rect
              x={0}
              y={animatedYOffset}
              width={scanBoxSize}
              height={4}
              opacity={opacity}>
              <LinearGradient
                start={vec(0, 0)}
                end={vec(scanBoxSize, 0)}
                colors={[
                  hexWithOpacity(scanLineColor, 0), // 左端透明
                  scanLineColor, // 中间颜色
                  hexWithOpacity(scanLineColor, 0), // 右端透明
                ]}
              />
            </Rect>
          </Canvas>
        </View>
        <SkiaMask></SkiaMask>
        {/* 四个角落的装饰线 */}
        <View
          style={[
            styles.cornerTL,
            {
              borderColor: theme.colors?.brand?.primary!,
              top: scanBoxTop - 2,
              left: scanBoxLeft - 2,
            },
          ]}
        />
        <View
          style={[
            styles.cornerTR,
            {
              borderColor: theme.colors?.brand?.primary!,
              top: scanBoxTop - 2,
              right: scanBoxLeft - 2,
            },
          ]}
        />
        <View
          style={[
            styles.cornerBL,
            {
              borderColor: theme.colors?.brand?.primary!,
              top: scanBoxSize + scanBoxTop - 18,
              left: scanBoxLeft - 2,
            },
          ]}
        />
        <View
          style={[
            styles.cornerBR,
            {
              borderColor: theme.colors?.brand?.primary!,
              top: scanBoxSize + scanBoxTop - 18,
              right: scanBoxLeft - 2,
            },
          ]}
        />
        {/* 提示文字 */}
        <Text
          style={[
            styles.tipText,
            {
              position: 'absolute',
              top: scanBoxTop + scanBoxSize + 22,
              width: scanBoxSize,
              textAlign: 'center',
              left: scanBoxLeft,
            },
          ]}>
          {t('device.QR.scan')}
        </Text>
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
  },
  scanBox: {
    width: scanBoxSize,
    height: scanBoxSize,
    borderWidth: 1,
    overflow: 'hidden',
    borderRadius: CORNER_RADIUS,
  },
  tipText: {
    fontSize: 13,
    zIndex: 20,
    color: '#fff',
  },
  // 左上角装饰
  cornerTL: {
    position: 'absolute',
    width: 20,
    height: 20,
    borderTopWidth: 4,
    borderLeftWidth: 4,
    borderTopLeftRadius: CORNER_RADIUS,
    zIndex: 20,
  },
  // 右上角装饰
  cornerTR: {
    position: 'absolute',
    width: 20,
    height: 20,
    borderTopWidth: 4,
    borderRightWidth: 4,
    borderTopRightRadius: CORNER_RADIUS,
    zIndex: 20,
  },
  // 左下角装饰
  cornerBL: {
    position: 'absolute',
    width: 20,
    height: 20,
    borderBottomWidth: 4,
    borderLeftWidth: 4,
    borderBottomLeftRadius: CORNER_RADIUS,
    zIndex: 20,
  },
  // 右下角装饰
  cornerBR: {
    position: 'absolute',
    width: 20,
    height: 20,
    borderBottomWidth: 4,
    borderRightWidth: 4,
    borderBottomRightRadius: CORNER_RADIUS,
    zIndex: 20,
  },
});
